package com.drojian.demo1.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.drojian.demo1.pojo.Fruit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.drojian.demo.R;

import java.util.List;


public class FruitAdapter extends ArrayAdapter<Fruit> {
    private final int resourceId;

    public FruitAdapter(@NonNull Context context, int textViewResourceId, @NonNull List<Fruit> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }


    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder= new ViewHolder();
            viewHolder.imgId = view.findViewById(R.id.fruitImage);
            viewHolder.name = view.findViewById(R.id.fruitName);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();

        }
        Fruit fruit = getItem(position);
        if (fruit != null) {
            viewHolder.imgId.setImageResource(fruit.getId());
            viewHolder.name.setText(fruit.getName());
        }
        return view;
    }
    static class ViewHolder {
        TextView name;
        ImageView imgId;

    }
}